<template>
  <!-- 登录框模式切换区域 -->
  <ul class="toggle">
    <li @click="toggleRight(0)" v-if="toggleNum"><i class="iconfont icon-msg"></i> 使用短信登录</li>
    <li @click="toggleRight(1)" v-else><i class="iconfont icon-user"></i> 使用账号登录</li>
  </ul>
  <div class="form">
    <!-- 账号密码登录区域 -->
    <Form ref="formCom" :validation-schema="formSchema">
      <template v-if="toggleNum">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field name="account" type="text" placeholder="请输入账号" v-model="form.account" />
          </div>
          <ErrorMessage name="account" v-slot="{ message }">
            <div class="error" v-if="message"><i class="iconfont icon-warning" />{{ message }}</div>
          </ErrorMessage>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field name="password" type="password" v-model="form.password" placeholder="请输入密码" />
          </div>
          <ErrorMessage name="password" v-slot="{ message }">
            <div class="error" v-if="message"><i class="iconfont icon-warning" />{{ message }}</div>
          </ErrorMessage>
        </div>
      </template>
      <!-- 手机号登录区域 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field name="mobile" v-model="form.mobile" type="text" placeholder="请输入手机号" />
          </div>
          <ErrorMessage name="mobile" v-slot="{ message }">
            <div class="error" v-if="message"><i class="iconfont icon-warning" />{{ message }}</div>
          </ErrorMessage>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field name="code" type="text" v-model="form.code" placeholder="请输入验证码" />
            <span class="code active" @click="getCodes">{{ time > 0 ? `${time}秒后重新获取` : '发送验证码' }}</span>
          </div>
          <ErrorMessage name="code" v-slot="{ message }">
            <div class="error" v-if="message"><i class="iconfont icon-warning" />{{ message }}</div>
          </ErrorMessage>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <!-- 自定义组件：Field as='需要渲染的组件名'-->
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <ErrorMessage name="isAgree" v-slot="{ message }">
          <div class="error" v-if="message"><i class="iconfont icon-warning" />{{ message }}</div>
        </ErrorMessage>
      </div>
      <a href="javascript:;" class="btn" @click="submit">登录</a>
    </Form>
  </div>
  <div class="action">
    <div class="url">
      <a href="javascript:;">忘记密码</a>
      <a href="javascript:;">免费注册</a>
    </div>
  </div>
</template>

<script>
import { Form, Field, ErrorMessage } from 'vee-validate' // 第三方表单验证组件
import schema from '@/utils/schema.js'
import { ref, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import Message from 'erabbit-ui/packages/components/Message'
import { getCode } from '@/api/user.js'
export default {
  components: { Form, Field, ErrorMessage },
  setup() {
    // 控制用户手机号登录还是账号密码登录
    const toggleNum = ref(1)
    const toggleRight = num => {
      toggleNum.value = num
    }
    // 收集登录数据
    const form = reactive({
      isAgree: false, // 协议勾选状态
      password: null, // 密码
      account: null, // 账号
      mobile: null, // 手机号
      code: null // 验证码
    })
    // 1.数据对象，==> form
    // 2.定制校验规则对象，==> formSchema
    // 3.使用校验规则，
    // 4.表单项指定校验规则，
    // 5.表单项绑定数据  ==> v-model
    // 6.使用错误组件显示错误信息 ==>ErrorMessage組件
    const { account, password, mobile, code, isAgree } = schema
    const formSchema = { account, password, mobile, code, isAgree }
    // 使用侦听器监听登录方式的变化重置数据
    watch(toggleNum, () => {
      form.password = null
      form.account = null
      form.mobile = null
      form.code = null
    })
    // 兜底校验
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const formCom = ref(null)
    const submit = async () => {
      // 对整个表单项进行校验
      const vali = await formCom.value.validate()
      // 校验成功
      if (vali) {
        // 账号登录
        if (toggleNum.value) {
          const { e, text } = await store.dispatch('user/getUserDate', {
            account: form.account,
            password: form.password
          })
          if (e) {
            Message({ type: 'success', text })
            await store.dispatch('cart/mergCart')
            // 跳转前查看是否有重定向地址，没有就跳首页
            router.push(route.query.redirectUrl || '/')
          } else {
            Message({ type: 'error', text })
          }
        } else {
          // 手机号登录
          if (num.value === 0) return Message({ type: 'error', text: '请先获取验证码' })
          const { e, text } = await store.dispatch('user/getUserDate', { mobile: form.mobile, code: form.code })
          if (e) {
            Message({ type: 'success', text })
            router.push('/')
          } else {
            Message({ type: 'error', text })
          }
        }
      }
    }
    // 获取验证码
    const time = ref(0)
    const num = ref(0)
    const codeKey = ref(true) // 获取验证码的标识，防止多次点击
    const getCodes = async () => {
      const valid = mobile(form.mobile)
      if (codeKey.value && valid === true) {
        num.value++
        codeKey.value = false
        time.value = 30
        const timeKey = setInterval(() => {
          time.value--
        }, 1000)
        // 获取短信验证码接口
        try {
          await getCode({ mobile: form.mobile })
        } catch (error) {
          Message({ type: 'error', text: error.response.data.message })
        }
        if (time.value === 0) {
          clearInterval(timeKey)
          codeKey.value = true
        }
      } else {
        if (valid === true) return
        Message({ type: 'error', text: valid })
      }
    }
    return {
      toggleNum,
      toggleRight,
      form,
      formSchema,
      submit,
      formCom,
      getCodes,
      time
    }
  }
}
</script>

<style lang="less" scoped>
.toggle {
  display: flex;
  flex-direction: row-reverse;
  padding: 15px 0;
  li {
    cursor: pointer; // 鼠标小手样式
    color: #27ba9b;
  }
}
.form-item {
  margin-bottom: 28px;
  .input {
    position: relative;
    input {
      border: 1px #27ba9b solid;
      height: 36px;
      width: 100%;
      padding: 0 0 0 40px;
      font-family: inherit;
      // &:focus {
      //   border-color: rgb(38, 19, 19); // 获得焦点时触发的选择器
      // }
    }
    .iconfont {
      width: 34px;
      height: 36px;
      line-height: 34px;
      text-align: center;
      font-size: 18px;
      background: #cfcdcd;
      color: #fff;
      position: absolute;
      left: 0;
    }
    .code {
      position: absolute;
      font-size: 12px;
      right: 1px;
      top: 1px;
      width: 90px;
      height: 34px;
      text-align: center;
      line-height: 34px;
      background: #f5f5f5;
      cursor: pointer;
    }
  }
  .error {
    color: red;
    position: absolute;
  }
}
.agree {
  a {
    color: #069;
  }
}
.btn {
  display: block;
  width: 100%;
  height: 40px;
  color: #fff;
  background: #27ba9b;
  line-height: 40px;
  text-align: center;
  font-size: 16px;
}
.url {
  padding: 20px 0;
  display: flex;
  flex-direction: row-reverse;
  a {
    color: #999;
    margin-left: 10px;
  }
}
</style>
